import './App.css';
import { useState, useEffect } from 'react';

function App() {
  // 状态管理
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedAnswers, setSelectedAnswers] = useState({});
  const [quizStarted, setQuizStarted] = useState(false);
  const [quizCompleted, setQuizCompleted] = useState(false);
  const [score, setScore] = useState(0);
  const [questions, setQuestions] = useState([]);
  const [quizTitle, setQuizTitle] = useState('');
  const [questionCount, setQuestionCount] = useState(5);
  const [loading, setLoading] = useState(false);

  // 生成随机题目
  const generateQuestions = () => {
    setLoading(true);
    // 模拟API请求延迟
    setTimeout(() => {
      const newQuestions = [];
      
      // 生成单选题
      for (let i = 0; i < questionCount; i++) {
        const question = generateRandomQuestion(i + 1);
        newQuestions.push(question);
      }
      
      setQuestions(newQuestions);
      setCurrentQuestionIndex(0);
      setSelectedAnswers({});
      setQuizStarted(true);
      setQuizCompleted(false);
      setScore(0);
      setLoading(false);
    }, 1000);
  };

  // 生成单个随机题目
  const generateRandomQuestion = (index) => {
    const questionTypes = [
      {
        text: `JavaScript中，以下哪个不是基本数据类型？`,
        options: ['String', 'Number', 'Object', 'Boolean'],
        answer: 2
      },
      {
        text: `React中，useState Hook的作用是什么？`,
        options: ['处理副作用', '管理组件状态', '处理DOM操作', '实现路由'],
        answer: 1
      },
      {
        text: `CSS中，以下哪个属性用于设置元素的背景颜色？`,
        options: ['color', 'text-color', 'background-color', 'bg-color'],
        answer: 2
      },
      {
        text: `HTML5中新增加的语义化标签不包括哪个？`,
        options: ['<header>', '<section>', '<div>', '<nav>'],
        answer: 2
      },
      {
        text: `以下哪种排序算法的平均时间复杂度为O(n log n)？`,
        options: ['冒泡排序', '插入排序', '快速排序', '选择排序'],
        answer: 2
      },
      {
        text: `在Promise中，以下哪个方法用于处理成功的结果？`,
        options: ['.then()', '.catch()', '.finally()', '.error()'],
        answer: 0
      },
      {
        text: `以下哪个不是前端框架或库？`,
        options: ['React', 'Django', 'Vue', 'Angular'],
        answer: 1
      },
      {
        text: `CSS Grid布局主要用于创建什么类型的布局？`,
        options: ['一维布局', '二维布局', '响应式布局', '流式布局'],
        answer: 1
      }
    ];
    
    // 随机选择一个题目类型
    const randomType = questionTypes[Math.floor(Math.random() * questionTypes.length)];
    
    return {
      id: index,
      text: randomType.text,
      options: randomType.options,
      answer: randomType.answer
    };
  };

  // 选择答案
  const handleAnswerSelect = (optionIndex) => {
    setSelectedAnswers(prev => ({
      ...prev,
      [currentQuestionIndex]: optionIndex
    }));
  };

  // 下一题
  const handleNextQuestion = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(prev => prev + 1);
    }
  };

  // 上一题
  const handlePrevQuestion = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  // 提交答案
  const handleSubmit = () => {
    let newScore = 0;
    questions.forEach((question, index) => {
      if (selectedAnswers[index] === question.answer) {
        newScore++;
      }
    });
    setScore(newScore);
    setQuizCompleted(true);
  };

  // 重新开始
  const handleRestart = () => {
    setQuizStarted(false);
    setQuizCompleted(false);
    setQuestions([]);
    setQuizTitle('');
    setQuestionCount(5);
  };

  return (
    <div className="App">
      <header className="App-header">
        {!quizStarted ? (
          <div className="quiz-setup">
            <h1>编程知识问答</h1>
            <div className="setup-form">
              <div className="form-group">
                <label htmlFor="quiz-title">测验标题</label>
                <input
                  id="quiz-title"
                  type="text"
                  value={quizTitle}
                  onChange={(e) => setQuizTitle(e.target.value)}
                  placeholder="输入测验标题"
                />
              </div>
              <div className="form-group">
                <label htmlFor="question-count">题目数量</label>
                <input
                  id="question-count"
                  type="number"
                  min="1"
                  max="20"
                  value={questionCount}
                  onChange={(e) => setQuestionCount(parseInt(e.target.value) || 5)}
                />
              </div>
              <button 
                className="start-button" 
                onClick={generateQuestions}
                disabled={loading}
              >
                {loading ? '生成题目中...' : '开始测验'}
              </button>
            </div>
          </div>
        ) : quizCompleted ? (
          <div className="quiz-results">
            <h2>{quizTitle || '编程知识问答'} 结果</h2>
            <div className="score-display">
              <p>你的得分: {score} / {questions.length}</p>
              <p>正确率: {Math.round((score / questions.length) * 100)}%</p>
            </div>
            <button className="restart-button" onClick={handleRestart}>重新开始</button>
          </div>
        ) : (
          <div className="quiz-container">
            <h2>{quizTitle || '编程知识问答'}</h2>
            <div className="question-counter">
              第 {currentQuestionIndex + 1} 题 / 共 {questions.length} 题
            </div>
            {questions.length > 0 && (
              <div className="question-card">
                <div className="question-text">
                  {questions[currentQuestionIndex].text}
                </div>
                <div className="options-container">
                  {questions[currentQuestionIndex].options.map((option, index) => (
                    <div
                      key={index}
                      className={`option ${selectedAnswers[currentQuestionIndex] === index ? 'selected' : ''}`}
                      onClick={() => handleAnswerSelect(index)}
                    >
                      {String.fromCharCode(65 + index)}. {option}
                    </div>
                  ))}
                </div>
                <div className="navigation-buttons">
                  <button 
                    onClick={handlePrevQuestion}
                    disabled={currentQuestionIndex === 0}
                  >
                    上一题
                  </button>
                  {currentQuestionIndex === questions.length - 1 ? (
                    <button onClick={handleSubmit}>提交答案</button>
                  ) : (
                    <button onClick={handleNextQuestion}>下一题</button>
                  )}
                </div>
              </div>
            )}
          </div>
        )}
      </header>
    </div>
  );
}

export default App;